package com.cction.comm;

import android.content.Context;


import com.cction.entry.HouseBean;
import com.cction.entry.SaveHouseDataBean;
import com.google.gson.Gson;

import java.util.ArrayList;

/**
 * 房贷操作
 */
public class SaveHouseUtils {
    public static final String DATAKEY = "housekey";
    public static SaveHouseDataBean saveHouseDataBean;

    /**
     * 初始化
     *
     * @return
     */
    public static SaveHouseDataBean init() {
        SaveHouseDataBean saveHouseDataBean = new SaveHouseDataBean();
        ArrayList<HouseBean> arrayList = new ArrayList<>();
        saveHouseDataBean.arrayList = arrayList;
        return saveHouseDataBean;
    }

    /**
     * 获取数据
     */
    public static SaveHouseDataBean readData(Context context) {
        String value = (String) SPUtils.get(context, DATAKEY, "");
        if (value.isEmpty()) {
            return init();
        }
        saveHouseDataBean = new Gson().fromJson(value, SaveHouseDataBean.class);
        if (saveHouseDataBean != null) {
            return saveHouseDataBean;
        }
        return init();
    }

    /**
     * 写入数据
     */
    public static void wirteData(Context context, HouseBean houseBean) {
        if (saveHouseDataBean == null) {
            saveHouseDataBean = readData(context);
        }
        saveHouseDataBean.arrayList.add(houseBean);
        String value = new Gson().toJson(saveHouseDataBean);
        SPUtils.put(context, DATAKEY, value);
    }

    /**
     * 删除
     */
    public static void remove(Context context, HouseBean houseBean) {
        if (saveHouseDataBean == null) {
            saveHouseDataBean = readData(context);
        }
        int size = saveHouseDataBean.arrayList.size();
        for (int i = 0; i < size; i++) {
            HouseBean bean = saveHouseDataBean.arrayList.get(i);
            if (bean.id.equals(houseBean.id)) {
                saveHouseDataBean.arrayList.remove(i);
                break;
            }
        }
        String value = new Gson().toJson(saveHouseDataBean);
        SPUtils.put(context, DATAKEY, value);
    }


    /**
     * 清空数据
     */
    public static void clear(Context context) {
        saveHouseDataBean = null;
        SPUtils.put(context, DATAKEY, "");
    }
}
